博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
JS动态引入js,CSS——动态创建script/link/style标签
阅读量:4124 次
发布时间:2019-05-25

本文共 1414 字,大约阅读时间需要 4 分钟。

一.动态创建link方式

我们可以使用link的方式.如下代码所示.

function addCssByLink(url){	var doc=document;	var link=doc.createElement("link");	link.setAttribute("rel", "stylesheet");    link.setAttribute("type", "text/css");    link.setAttribute("href", url);	var heads = doc.getElementsByTagName("head");	if(heads.length)		heads[0].appendChild(link);	else		doc.documentElement.appendChild(link);}

 

二.动态创建style方式

但是,这样的话,需要加载整个css文件,但是那样有可能浪费一个http请求并占用一个服务器请求数,并等待上一段下载时间,所以,Firebug Lite采取的是将css代码写在js中,然后动态创建style标签的方法,正如下面所示

function addCssByStyle(cssString){	var doc=document;	var style=doc.createElement("style");	style.setAttribute("type", "text/css");	if(style.styleSheet){// IE		style.styleSheet.cssText = cssString;	} else {// w3c		var cssText = doc.createTextNode(cssString);		style.appendChild(cssText);	}	var heads = doc.getElementsByTagName("head");	if(heads.length)		heads[0].appendChild(style);	else		doc.documentElement.appendChild(style);}

这样的话,如果是较少的代码,可以比较方便的实现到动态加载css的效果,但是如果为了方便维护和管理,并没有等待时间限制,使用link方式更加合适

三.动态创建script方式

var script=document.createElement("script");script.setAttribute("type", "text/javascript");script.setAttribute("src", "JustWalking.js");var heads = document.getElementsByTagName("head");if(heads.length)	heads[0].appendChild(script);else	document.documentElement.appendChild(script);

但是这种方式在IE内核的浏览器中支持,在google、360极速、firefox下却不行

四.打印引入style方式

 

document.write("
");

五.打印引入js方式

document.write("");

 

 

 

 

 

 

 

 

 

 

 

 

 

 

转载地址:http://felpi.baihongyu.com/

你可能感兴趣的文章
Sub-process /usr/bin/dpkg returned an error code (1) 的解决办法
查看>>
ubuntu安装google拼音输入法
查看>>
ArrayList与LinkedList的区别
查看>>
GoogleCode SVN应用(源代码学习)
查看>>
ubuntu下hadoop环境的配置
查看>>
ubuntu下删除和新建用户
查看>>
hadoop平台运行WordCount程序
查看>>
ubuntu配置软件镜像源(提升下载速度)
查看>>
myeclipse配置hadoop开发环境
查看>>
install-info error during update
查看>>
Agent admitted failure to sign using the key
查看>>
ubuntu解决包依赖关系
查看>>
ubuntu 安装ffmpeg1.0 , opencv2.4.2
查看>>
MyEclipse安装CDT插件
查看>>
ubuntu下eclipse集成OpenCv
查看>>
OpenCv将图片写入到视频文件中
查看>>
在csdn博客上添加qq聊天窗口插件
查看>>
launch failed.Binary not found(CDT---eclipse编写c++出现的问题)
查看>>
Qt开发的程序添加ico图标
查看>>
三系统安装win7+ubuntu+win8以及出现的问题
查看>>